import os
import re

book_dict = {}
per_line = 50
per_page = 10

def get_books():
    files = os.listdir('books/')
    # print(files)

    # book_dict = {}
    for txt in files:
        file_path = os.path.abspath('books')
        file_abspath = os.path.join(file_path, txt)
        # print(file_abspath)
        book_dict[txt.split('.')[0]] = file_abspath

    print('可查看书籍为：' + str(list(book_dict.keys())))

 
def read_book(book_name):
    # print('select book :' + book_name)
    file_abspath = book_dict[book_name]

    # print('book path is:' + file_abspath)
    book_buffer, section_list = open_book(file_abspath)

    for count, section_dict in enumerate(section_list):
        # print(count)
        # print(section_dict)
        section = book_buffer[section_dict['begin']: section_dict['end']]
        current_section = section.split('\n')
        # print(current_section)

        print_line = 0
        for i, line in enumerate(current_section):
            while_or_not = 0
            while while_or_not * per_line <= len(line):
                to_print = line[per_line * while_or_not: per_line * (1 + while_or_not)]
                while_or_not += 1
                if to_print.strip():
                    print(to_print)
                    print_line += 1
                    if print_line % per_page == 0:
                        input_key = 0
                        while input_key != 'n':
                            input_key = input('输入n翻页:')
        input_key = 0
        while input_key != 'n':
            input_key = input('输入n查看下一章:')
        # break
        
        


### 打开书，并创建索引，待做记录
def open_book(book_path):
    section_list = []
    with open(book_path) as f:
        book_reading = re.sub('(\n)+', '\n', f.read().lstrip('\n'))
        # print(book_reading)
        sections = re.finditer('第.*章 .*', book_reading)
        # print(type(sections))
        for section in sections:
            section_list.append({'begin': int(section.span()[0]), 'section': book_reading[int(section.span()[0]): int(section.span()[1])]})
            try:
                section_list[-2]['end'] = int(section.span()[0])
            except:
                pass
        section_list[-1]['end'] = len(book_reading)
        # print(section_list[20:23])
        return book_reading, section_list
        


if __name__ == '__main__':
    get_books()
    read_book('三体')